/**
 * Copyright 2009-2011 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.myjung.manager.impl;

import java.util.List;

import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import net.myjung.Myjung;
import net.myjung.manager.AbstractMyManager;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * @author Steve M. Jung
 */
public class MyManager extends AbstractMyManager {
	private JavaMailSenderImpl mailSender;

	@Override
	protected void sendMail(InternetAddress from, List<InternetAddress> tos, List<InternetAddress> ccs, String subject, MimeBodyPart content,
			List<MimeBodyPart> attachments) throws Exception {
		MimeMessage mimeMsg = getMailSender().createMimeMessage();
		MimeMessageHelper msgHelper;
		msgHelper = new MimeMessageHelper(mimeMsg, true);

		msgHelper.setFrom(from);
		InternetAddress[] to = new InternetAddress[tos.size()];
		tos.toArray(to);
		msgHelper.setTo(to);
		if (!Myjung.isEmpty(ccs)) {
			InternetAddress[] cc = new InternetAddress[ccs.size()];
			ccs.toArray(cc);
			msgHelper.setCc(cc);
		}

		msgHelper.setSubject(subject);

		Multipart mp = new MimeMultipart();
		if (content != null)
			mp.addBodyPart(content);

		if (Myjung.isEmpty(attachments)) {
			for (MimeBodyPart attachment : attachments)
				mp.addBodyPart(attachment);
		}

		mimeMsg.setContent(mp);

		getMailSender().send(mimeMsg);
	}

	public JavaMailSenderImpl getMailSender() {
		return mailSender;
	}
	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}
}
